﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace Shc.Security
{
    /// <summary>
    /// 软创加密类
    /// </summary>
    public static class Cryptography
    {
        public static string Bytes2Hex(byte[] bytes)
        {
            string lin = "0123456789abcdef";
            string str = "";
            foreach (byte b in bytes)
            {
                str += lin[b >> 4];
                str += lin[b & 0x0f];
            }
            return str;
        }

        public static byte[] Hex2Bytes(string hex)
        {
            int c;
            if (1 == ((c = hex.Length) & 1))
            {
                return null;
            }
            c >>= 1;
            byte[] result = new byte[c];
            for (int i = 0, j = 0; i < c; i++)
            {
                int reg = 0;
                for (int k = 0; k < 2; k++)
                {
                    char val = hex[j++];
                    reg <<= 4;
                    if (('0' <= val) && ('9' >= val))
                    {
                        reg |= (int)(val - '0');
                    }
                    else if (('a' <= val) && ('f' >= val))
                    {
                        reg |= (int)(val - 'a') + 10;
                    }
                    else if (('A' <= val) && ('F' >= val))
                    {
                        reg |= (int)(val - 'A') + 10;
                    }
                    else
                    {
                        return null;
                    }
                }
                result[i] = (byte)reg;
            }
            return result;
        }

        /// <summary>
        /// MD5 加密静态方法
        /// </summary>
        /// <param name="EncryptString">待加密的密文</param>
        /// <returns>returns</returns>
        public static string MD5Encrypt(string EncryptString)
        {
            MD5 m_ClassMD5 = new MD5CryptoServiceProvider();
            
            try
            {
                return Bytes2Hex(m_ClassMD5.ComputeHash(Encoding.Default.GetBytes(EncryptString)));
            }
            catch { return null; }
            finally { m_ClassMD5.Clear(); }
        }

        /// <summary>
        /// DES 加密(数据加密标准，速度较快，适用于加密大量数据的场合)
        /// </summary>
        /// <param name="EncryptString">待加密的密文</param>
        /// <param name="EncryptKey">加密的密钥(密钥必须为8位)</param>
        /// <returns>returns</returns>
        public static string DESEncrypt(string EncryptString, string EncryptKey)
        {
            DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();
            try
            {
                if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); }
                if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); }
                if (EncryptKey.Length != 8) { throw (new Exception("密钥必须为8位")); }
                byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                string m_strEncrypt = "";
                byte[] m_btEncryptString = Encoding.UTF8.GetBytes(EncryptString);
                MemoryStream m_stream = new MemoryStream();
                CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateEncryptor(Encoding.UTF8.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);
                m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);
                m_cstream.FlushFinalBlock();
                m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
                m_stream.Close(); m_stream.Dispose();
                m_cstream.Close(); m_cstream.Dispose();
                return m_strEncrypt;
            }
            catch { return null; }
            finally { m_DESProvider.Clear(); }
        }

        /// <summary>
        /// DES 解密(数据加密标准，速度较快，适用于加密大量数据的场合)
        /// </summary>
        /// <param name="DecryptString">待解密的密文</param>
        /// <param name="DecryptKey">解密的密钥</param>
        /// <returns>returns</returns>
        public static string DESDecrypt(string DecryptString, string DecryptKey)
        {
             DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();
            try
            {
                if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }
                if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }
                if (DecryptKey.Length != 8) { throw (new Exception("密钥必须为8位")); }
                byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                string m_strDecrypt = "";
                byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);
                MemoryStream m_stream = new MemoryStream();
                CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateDecryptor(Encoding.UTF8.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);
                m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);
                m_cstream.FlushFinalBlock();
                m_strDecrypt = Encoding.UTF8.GetString(m_stream.ToArray());
                m_stream.Close(); m_stream.Dispose();
                m_cstream.Close(); m_cstream.Dispose();
                return m_strDecrypt;
            }
            catch { return null; }
            finally { m_DESProvider.Clear(); }
        }

        /// <summary>
        /// RC2 加密(用变长密钥对大量数据进行加密)
        /// </summary>
        /// <param name="EncryptString">待加密密文</param>
        /// <param name="EncryptKey">加密密钥</param>
        /// <returns>returns</returns>
        public static string RC2Encrypt(string EncryptString, string EncryptKey)
        {
            RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider();
            try
            {
                if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); }
                if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); }
                if (EncryptKey.Length < 5 || EncryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); }
                string m_strEncrypt = "";
                byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString);
                MemoryStream m_stream = new MemoryStream();
                CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);
                m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);
                m_cstream.FlushFinalBlock();
                m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
                m_stream.Close(); m_stream.Dispose();
                m_cstream.Close(); m_cstream.Dispose();
                return m_strEncrypt;
            }
            catch { return null; }
            finally { m_RC2Provider.Clear(); }
        }

        /// <summary>
        /// RC2 解密(用变长密钥对大量数据进行加密)
        /// </summary>
        /// <param name="DecryptString">待解密密文</param>
        /// <param name="DecryptKey">解密密钥</param>
        /// <returns>returns</returns>
        public static string RC2Decrypt(string DecryptString, string DecryptKey)
        {
            RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider();
            try
            {
                if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }
                if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }
                if (DecryptKey.Length < 5 || DecryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); }
                byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
                string m_strDecrypt = "";
                byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);
                MemoryStream m_stream = new MemoryStream();
                CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);
                m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);
                m_cstream.FlushFinalBlock();
                m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());
                m_stream.Close(); m_stream.Dispose();
                m_cstream.Close(); m_cstream.Dispose();
                return m_strDecrypt;
            }
            catch { return null; }
            finally { m_RC2Provider.Clear(); }
        }

        /// <summary>
        /// 3DES 加密(基于DES，对一块数据用三个不同的密钥进行三次加密，强度更高)
        /// </summary>
        /// <param name="EncryptString">待加密密文</param>
        /// <param name="EncryptKey1">密钥一</param>
        /// <param name="EncryptKey2">密钥二</param>
        /// <param name="EncryptKey3">密钥三</param>
        /// <returns>returns</returns>
        public static string DES3Encrypt(string EncryptString, string EncryptKey1, string EncryptKey2, string EncryptKey3)
        {
            return DESEncrypt(DESEncrypt(DESEncrypt(EncryptString, EncryptKey3), EncryptKey2), EncryptKey1);
        }

        /// <summary>
        /// 3DES 解密(基于DES，对一块数据用三个不同的密钥进行三次加密，强度更高)
        /// </summary>
        /// <param name="DecryptString">待解密密文</param>
        /// <param name="DecryptKey1">密钥一</param>
        /// <param name="DecryptKey2">密钥二</param>
        /// <param name="DecryptKey3">密钥三</param>
        /// <returns>returns</returns>
        public static string DES3Decrypt(string DecryptString, string DecryptKey1, string DecryptKey2, string DecryptKey3)
        {
            return DESDecrypt(DESDecrypt(DESDecrypt(DecryptString, DecryptKey1), DecryptKey2), DecryptKey3);
        }

        /// <summary>
        /// AES 加密(高级加密标准，是下一代的加密算法标准，速度快，安全级别高，目前 AES 标准的一个实现是 Rijndael 算法)
        /// </summary>
        /// <param name="EncryptString">待加密密文</param>
        /// <param name="EncryptKey">加密密钥,AES设计有三个密钥长度:128(16字符),192(24字符),256(32字符)位</param>
        /// <returns></returns>
        public static string AESEncrypt(string EncryptString, string EncryptKey)
        {
            Rijndael m_AESProvider = Rijndael.Create();
            try
            {
                if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); }
                if (string.IsNullOrEmpty(EncryptKey)) { throw (new Exception("密钥不得为空")); }
                string m_strEncrypt = "";
                byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");
                byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString);
                MemoryStream m_stream = new MemoryStream();
                CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);
                m_csstream.Write(m_btEncryptString, 0, m_btEncryptString.Length); m_csstream.FlushFinalBlock();
                m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
                m_stream.Close(); m_stream.Dispose();
                m_csstream.Close(); m_csstream.Dispose();
                return m_strEncrypt;
            }
            catch { return null; }
            finally { m_AESProvider.Clear(); }
        }


        /// <summary>
        /// AES 解密(高级加密标准，是下一代的加密算法标准，速度快，安全级别高，目前 AES 标准的一个实现是 Rijndael 算法)
        /// </summary>
        /// <param name="DecryptString">待解密密文</param>
        /// <param name="DecryptKey">解密密钥</param>
        /// <returns></returns>
        public static string AESDecrypt(string DecryptString, string DecryptKey)
        {
            Rijndael m_AESProvider = Rijndael.Create();
            try
            {
                if (string.IsNullOrEmpty(DecryptString)) { throw (new Exception("密文不得为空")); }
                if (string.IsNullOrEmpty(DecryptKey)) { throw (new Exception("密钥不得为空")); }
                string m_strDecrypt = "";
                byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");
                byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);
                MemoryStream m_stream = new MemoryStream();
                CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);
                m_csstream.Write(m_btDecryptString, 0, m_btDecryptString.Length); m_csstream.FlushFinalBlock();
                m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());
                m_stream.Close(); m_stream.Dispose();
                m_csstream.Close(); m_csstream.Dispose();
                return m_strDecrypt;
            }
            catch { return null; }
            finally { m_AESProvider.Clear(); }
        }

        #region DESEnCode DES加密
        /// <summary>
        /// DES加密，使用默认算法
        /// </summary>
        /// <param name="pToEncrypt">明文</param>
        /// <param name="sKey">密钥</param>
        /// <returns></returns>
        public static string DESEnCode(string pToEncrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);

            //建立加密对象的密钥和偏移量   
            //原文使用ASCIIEncoding.ASCII方法的GetBytes方法   
            //使得输入密码必须输入英文文本   
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            return Convert.ToBase64String(ms.ToArray());
        }
        #endregion

        #region DESDeCode DES解密
        /// <summary>
        /// DES解密，使用默认算法
        /// </summary>
        /// <param name="pToDecrypt">密文</param>
        /// <param name="sKey">密钥</param>
        /// <returns></returns>
        public static string DESDeCode(string pToDecrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder ret = new StringBuilder();

            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }
        #endregion 
    }
}